package simulaco.dao;

import gminet.infra.dao.DataAccessObject;
import gminet.infra.db.TransactionException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import simulaco.dto.Instituicao;
import simulaco.dto.Situacao;

public class InstituicaoDAO extends DataAccessObject {

    public static Instituicao findByPK(int instituicaoId, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT A.CD_INSTITUICAO  CD_INSTITUICAO ");
        sbSql.append("     , A.TX_NOME         TX_NOME        ");
        sbSql.append("     , A.ID_SITUACAO     ID_SITUACAO    ");
        sbSql.append("     , A.TS_CADASTRO     TS_CADASTRO    ");
        sbSql.append("  FROM INSTITUICAO        A ");
        sbSql.append(" WHERE A.CD_INSTITUICAO = ? ");

        Instituicao instituicao = null;
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            setInt(ps, 1, instituicaoId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                instituicao = fromResultSet(rs);
            }
            close(ps);
        } catch (SQLException sqle) {
            throw new TransactionException("InstituicaoDAO.findByPK (" + sqle.getMessage() + ")");
        }
        return instituicao;
    }

    public static List<Instituicao> findAll(Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT A.CD_INSTITUICAO  CD_INSTITUICAO ");
        sbSql.append("     , A.TX_NOME         TX_NOME        ");
        sbSql.append("     , A.ID_SITUACAO     ID_SITUACAO    ");
        sbSql.append("     , A.TS_CADASTRO     TS_CADASTRO    ");
        sbSql.append("  FROM INSTITUICAO  A ");
        sbSql.append(" ORDER BY A.TX_NOME   ");
        List<Instituicao> instituicaosList = new ArrayList<Instituicao>(100);
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Instituicao instituicao = fromResultSet(rs);
                instituicaosList.add(instituicao);
            }
            close(rs);
        } catch (SQLException sqle) {
            throw new TransactionException("InstituicaoDAO.findAll (" + sqle.getMessage() + ")");
        }
        return instituicaosList;
    }
    
    public static List<Instituicao> findByFilter(InstituicaoFilter filter, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT A.CD_INSTITUICAO  CD_INSTITUICAO ");
        sbSql.append("     , A.TX_NOME         TX_NOME        ");
        sbSql.append("     , A.ID_SITUACAO     ID_SITUACAO    ");
        sbSql.append("     , A.TS_CADASTRO     TS_CADASTRO    ");
        sbSql.append("  FROM INSTITUICAO  A ");
        sbSql.append(" WHERE 1 = 1 ");
        if (filter.hasPrimeiroDigito()) {
            String strLetra = filter.getPrimeiroDigito().toLowerCase();
            if (strLetra.equalsIgnoreCase("0")) {
                sbSql.append(" AND LEFT(A.TX_NOME, 1) < 'A'");
            } else {
                sbSql.append(" AND LOWER(A.TX_NOME) like '" + strLetra + "%' ");
            }
        }
        if (filter.hasNome()) {
            String strName = filter.getNome().toLowerCase();
            sbSql.append(" AND LOWER(A.TX_NOME) like '%" + strName + "%' ");
        }
        if (filter.hasCodigoSituacao()) {
            sbSql.append(" AND A.ID_SITUACAO = ? ");
        }
        sbSql.append(" ORDER BY A.TX_NOME   ");
        List<Instituicao> instituicaoList = new ArrayList<Instituicao>(100);
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            int pos = 1;
            if (filter.hasCodigoSituacao()) {
                setInt(ps, pos++, filter.getCodigoSituacao());
            }
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Instituicao instituicao = fromResultSet(rs);
                instituicaoList.add(instituicao);
            }
            close(rs);
        } catch (SQLException sqle) {
            throw new TransactionException("InstituicaoDAO.findByFilter (" + sqle.getMessage() + ")");
        }
        return instituicaoList;
    }

    public static void insert(Instituicao instituicao, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("INSERT INTO INSTITUICAO ");
        sbSql.append("     ( CD_INSTITUICAO   ");
        sbSql.append("     , TX_NOME          ");
        sbSql.append("     , ID_SITUACAO      ");
        sbSql.append("     , TS_CADASTRO      ");
        sbSql.append(") VALUES (?,?,?,?)");
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            int pos = 1;
            setInt(ps, pos++, instituicao.getCodigo());
            setString(ps, pos++, instituicao.getNome());
            setInt(ps, pos++, instituicao.getSituacao().getCodigo());
            setTimestamp(ps, pos++, instituicao.getDataCadastro());
            //
            ps.executeUpdate();
            close(ps);
        } catch (SQLException sqle) {
            throw new TransactionException("InstituicaoDAO.insert (" + sqle.getMessage() + ")");
        }
    }

    public static void update(Instituicao instituicao, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("UPDATE INSTITUICAO        ");
        sbSql.append("   SET TX_NOME        = ? ");
        sbSql.append("     , ID_SITUACAO    = ? ");
        sbSql.append(" WHERE CD_INSTITUICAO = ? ");
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            int pos = 1;
            setString(ps, pos++, instituicao.getNome());
            setInt(ps, pos++, instituicao.getSituacao().getCodigo());
            setInt(ps, pos++, instituicao.getCodigo());
            //
            ps.executeUpdate();
            close(ps);
        } catch (SQLException sqle) {
            throw new TransactionException("InstituicaoDAO.update (" + sqle.getMessage() + ")");
        }
    }

    public static void delete(Instituicao instituicao, Connection conn) throws TransactionException {

        StringBuffer sbSql = new StringBuffer();
        sbSql.append("DELETE FROM INSTITUICAO  ");
        sbSql.append(" WHERE CD_INSTITUICAO = ?");
        try {
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            setInt(ps, 1, instituicao.getCodigo());
            ps.executeUpdate();
            close(ps);
        } catch (SQLException sqle) {
            throw new TransactionException("InstituicaoDAO.delete (" + sqle.getMessage() + ")");
        }
    }

    public static int getNextCodigo(Connection conn, int iRange, int eRange) throws TransactionException {

        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("SELECT MAX(CD_INSTITUICAO) AS CD_MAX ");
            sbSql.append("  FROM INSTITUICAO        ");
            sbSql.append(" WHERE CD_INSTITUICAO > ? ");
            sbSql.append("   AND CD_INSTITUICAO < ? ");
            //
            PreparedStatement ps = conn.prepareStatement(sbSql.toString());
            setInt(ps, 1, iRange);
            setInt(ps, 2, eRange);
            ResultSet rs = ps.executeQuery();
            int max = 0;
            if (rs.next()) {
                max = rs.getInt("CD_MAX");
            }
            close(rs);
            return (max != 0 ? max : iRange) + 1;
        } catch (SQLException sqlEx) {
            throw new TransactionException(sqlEx);
        }
    }

    private static Instituicao fromResultSet(ResultSet rs) throws SQLException {

        // INSTITUICAO
        Instituicao instituicao = new Instituicao();
        instituicao.setCodigo(getInt(rs, "CD_INSTITUICAO"));
        instituicao.setNome(getString(rs, "TX_NOME"));
        instituicao.setSituacao(Situacao.getSituacaoById(getByte(rs, "ID_SITUACAO")));
        instituicao.setDataCadastro(getDateFromTimestamp(rs, "TS_CADASTRO"));
        //
        return instituicao;
    }

}
